var NodeRSA = require('node-rsa')

var fs = require('fs')

function generator() {
  var key = new NodeRSA({ b: 512 })
  key.setOptions({ encryptionScheme: 'pkcs1' })
  var privatePem = key.exportKey('pkcs1-private-pem')
  var publicPem = key.exportKey('pkcs1-public-pem')
  fs.writeFile('./pem/public.pem', publicPem, (err) => {
    if (err) throw err
    console.log('公钥已保存！')
  })
  fs.writeFile('./pem/private.pem', privatePem, (err) => {
    if (err) throw err
    console.log('私钥已保存！')
  })
}

// generator();


function encrypt(str) {
  return new Promise((resolve)=>{
    fs.readFile('./pem/private.pem', function (err, data) {
      var key = new NodeRSA(data);
      let cipherText = key.encryptPrivate(str, 'base64');
      // console.log(cipherText);
      resolve(cipherText);
    });
  });
}

function decrypt(str) {
  return new Promise((resolve)=>{
    fs.readFile('./pem/public.pem', function (err, data) {
      var key = new NodeRSA(data);
      let rawText = key.decryptPublic(str, 'utf8');
      // console.log(rawText);
      resolve(rawText);
    });
  });
}
// generator();
//encrypt();
// decrypt();

module.exports = {
  encrypt,
  decrypt
};